/**
 * zmn渠道管理-详情
 * 文件命名格式：zmn.模块.表/功能.js
 * @author xiangjunming
 * @since 2019/08/22 18:06
 */
layui.define(['form', 'layedit', 'laydate', 'xmSelect', 'zmnBind', 'table', 'laypage', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var laypage = layui.laypage
    var xmSelect = layui.xmSelect;
    let zmnSelect = layui.zmnSelect;
    var zmnBind = layui.zmnBind;
    var table = layui.table;
    zmnLayUtil.layFormVerify(form);
    let selectedAbutmentDeptId = json.obj.abutmentDeptId;
    let selectedSalesmanDeptId = json.obj.deptId;

    let requiredContractTimeRange = true;
    let channelInfoVerifyFlag = true;

    if (json.obj.channelType == 4) {
        requiredContractTimeRange = false;
        channelInfoVerifyFlag = false;
    }

    // 自定义验证规则
    form.verify({
        phone: function (value) {
            if (value && value.indexOf("*") == -1) {
                if (value.length > 11) {
                    return "电话号码长度不能超过11位";
                }
                if (!/^[0-9]+$/.test(value)) {
                    return "电话号码只能是数字";
                }
            }
        },
        contractTimeRange: function (value) {
            // 判断是否为必填
            if (requiredContractTimeRange && zmnUtil.isEmptyNull(value)) {
                return "请输入合同起止日期";
            }
        },
        mobileVerify: function (val) {
            if (channelInfoVerifyFlag && zmnUtil.isEmptyNull(val)) {
                return "请输入联系电话"
            }
        },
        contactVerify: function (val) {
            if (channelInfoVerifyFlag && zmnUtil.isEmptyNull(val)) {
                return "请输入联系人"
            }
        }

    });
    // 电话的修改，带有*获取焦点的时候清空文本，如果没有输入
    let lastVal = "";
    $("#mobile").focus(function () {
        lastVal = $(this).val();
        if (lastVal.indexOf("*") != -1) {
            $(this).val(lastVal.substring(0, 1));
        }
    });

    $("#mobile").blur(function () {
        let val = $(this).val();
        if (val && val == lastVal.substring(0, 1)) {
            $(this).val(lastVal);
        }
    });

    if (json.obj.channelType == 4) {
        // 不显示合同起止日期
        $("#hideContractTimeRange").hide();
        channelInfoVerifyFlag = false;
        // 不显示渠道方信息
        $('#channel-info').hide();
        channelInfoVerifyFlag = false
    }

    form.on('select(channelType)', function (obj) {
        changeChannelType(obj.value);
    })

    function changeChannelType(val) {
        // 自有渠道
        if (val == 4) {
            // 不显示合同起止日期
            $("#hideContractTimeRange").hide();
            requiredContractTimeRange = false;
        } else {
            $("#hideContractTimeRange").show();
            requiredContractTimeRange = true;
        }
        // 个人渠道
        if (val == 7) {
            $("#companyIdDiv").hide();
        } else {
            $("#companyIdDiv").show();
        }

        // 渠道方信息
        if (val == 4) {
            $('#channel-info').hide();
            channelInfoVerifyFlag = false;
        } else {
            $('#channel-info').show();
            channelInfoVerifyFlag = true;
        }
    }

    if (json.obj.channelId > 0) {
        table.init('zmn-table', {
            limit: json.pageSize,
            page: true
        })
        laypage.render(layui.$.extend({limits: [10]}, zmnPage.laypageOptions(json)));
    }

    function remoteCall(url, keyword, deptId, selecter) {
        function _getPlat() {
            return 0;
        }

        let data = null;
        $.ajax({
            type: 'get',
            url: url,
            data: {keyword: keyword, deptId: deptId, plat: _getPlat()},
            dataType: "json",
            success: function (resp) {
                selecter.select.update({
                    data: resp.data,
                    initValue: (new Array()),
                    autoRow: true,
                })
            },
            error: function (XMLHttpRequest, status, errorThrown) {

            }
        });

        return data;
    };

    function selectedAbutmentDeptIdCallback(url) {
        if (zmnUtil.isNotNull(selectedAbutmentDeptId)) {
            url += "?deptId=" + selectedAbutmentDeptId;
        }
        return url;
    }

    function selectedDeptIdCallback(url) {

        if (zmnUtil.isNotNull(selectedSalesmanDeptId)) {
            url += "?deptId=" + selectedSalesmanDeptId;
        }
        return url;
    }

    function initSearch(divId, url, keyword, deptIdCallback, selectedValues, selectedCallback) {

        function _getPlat() {
            if (divId == 'abutmenter' || divId == 'salesman') {
                return 0;
            } else {
                return $('#plat').val();
            }
        }

        function newUrl(url) {
            if (zmnUtil.isNotNull(deptIdCallback)) {
                return deptIdCallback(url)
            }
            return url;
        }


        function _remoteCall(val, cb, show) {
            //这里如果val为空, 则不触发搜索
            if (!val) {
                return cb([]);
            }
            $.ajax({
                type: 'get',
                url: newUrl(url),
                data: {keyword: val, plat: _getPlat()},
                dataType: "json",
                success: function (resp) {
                    cb(resp.data)
                },
                error: function (XMLHttpRequest, status, errorThrown) {
                    cb([]);
                }
            });
        };
        let _select = xmSelect.render({
            el: '#' + divId,
            name: divId,
            disabled: zmnUtil.isNotNull(json.obj.companyId) && divId == 'companyId' ? true : false,
            radio: true,
            autoRow: true,
            toolbar: {show: false},
            list: [],
            filterable: true,
            remoteSearch: true,
            remoteMethod: _remoteCall,
            on: function (data) {
                //arr:  当前多选已选中的数据
                var arr = data.arr;
                //change, 此次选择变化的数据,数组
                var change = data.change;
                //isAdd, 此次操作是新增还是删除
                var isAdd = data.isAdd;
                //可以return一个数组, 代表想选中的数据
                //return []
                if (selectedCallback && arr.length > 0 && change.length > 0) {
                    selectedCallback(arr[0].value);
                }
            },
        })

        function _reload(callback) {
            _remoteCall(keyword, (data) => {
                _select.update({data: data});
                _select.setValue(selectedValues);
                if (callback) {
                    callback(data);
                }
            })
        }

        if (keyword) {
            _reload();
        }
        //name:()=>xmSelect.get('#'+divId)[0].getValue('textStr')[0].text
        return {
            value: () => _select.getValue('valueStr'),
            name: () => _select.getValue('nameStr'),
            deptName: () => _select.getValue() != null && _select.getValue().length > 0 ? _select.getValue()[0].deptName : '',
            staffName: () => _select.getValue() != null && _select.getValue().length > 0 ? _select.getValue()[0].staffName : '',
            select: _select,
            reload: _reload
        };
    }

    function toSplitStaffName(staffName) {
        if (staffName != null && staffName.indexOf('-') >= 0) {
            // xx部-xx人
            return staffName.split('-')[1];
        }
        return staffName;
    }

    let _companyId = initSearch("companyId", '/channel/search/company', json.obj.companyId, null, [json.obj.companyId], companyIdChange);

    let _salesman, _abutmenter, _receiver, _parent;
    _salesman = initSearch("salesman", '/channel/search/staff', toSplitStaffName(json.obj.salesmanName), selectedDeptIdCallback, [json.obj.salesman], checkSalesmanDeptId);
    _abutmenter = initSearch("abutmenter", '/channel/search/staff', toSplitStaffName(json.obj.abutmenterName), selectedAbutmentDeptIdCallback, [json.obj.abutmenter], checkAbutmentDeptId);
    _receiver = initSearch("receiver", '/channel/search/staff', toSplitStaffName(json.obj.receiverName), null, [json.obj.receiver]);
    if (json.rank == 2) {
        _parent = initSearch("parentId", '/channel/search?rank=1', json.obj.parentId, null, [json.obj.parentId], parentIdChange);
    }

    if (json.rank == 2) {
        _parent = initSearch("parentSourceId", '/channel/search?rank=1', json.obj.parentSourceId, null, [json.obj.parentSourceId], parentIdChange);
    }

    form.render(null, "zmn-form");
    laydate.render({elem: "#contractTimeRange", range: true, format: 'yyyy/MM/dd'});

    function parentIdChange(parentId) {
        $.ajax({
            async: false,
            type: "GET", url: "/channel/" + parentId, dataType: "json",
            success: function (obj) {
                let data = {
                    'companyId': obj.companyId,
                    'channelType': obj.channelType,
                    'level': obj.level,
                    'industryId': obj.industryId,
                    'platformType': obj.platformType,
                    'customerType': obj.customerType,
                    'plat': obj.plat,
                    'provinceId': obj.provinceId,
                    'cityId': obj.cityId,
                    'address': obj.address
                };
                for (var key in data) {
                    if (!zmnUtil.isEmptyNull(json.obj[key])) {
                        delete data[key];
                    }
                }
                form.val("zmn-form", data);
                if (!zmnUtil.isEmptyNull(data.channelType)) {
                    changeChannelType(data.channelType)
                }
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });
    }

    function companyIdChange(companyId) {
        if (json.rank == 1) {
            var url = "/channel/getCompanyById?companyId=" + companyId;
            $.ajax({
                async: false,
                type: "GET", url: url, dataType: "json",
                success: function (obj) {
                    let data = {
                        'plat': obj.plat
                    };
                    triggerCityOptions(data.provinceId);
                    form.val("zmn-form", data);

                    // 渲染合同模式
                    renderContractModel(obj.plat);
                    // 根据平台渲染子公司  如果是子公司合同则根据平台渲染子公司下拉框
                    triggerSubCompanyOptions(obj.plat);
                    // 选择平台联动一级部门
                    // triggerOneDeptOptions(obj.plat);
                },
                error: function (XMLHttpRequest, status, errorThrown) {
                }
            });
        }
    }

    function checkAbutmentDeptId() {
        if (zmnUtil.isEmptyNull(selectedAbutmentDeptId)) {

            layer.msg('运营部门必填！', {icon: 2});
            return false;
        }
    }

    function checkSalesmanDeptId() {
        if (zmnUtil.isEmptyNull(selectedSalesmanDeptId)) {

            layer.msg('商务部门必填！', {icon: 2});
            return false;
        }
    }


    form.on("radio(settle)", function (obj) {
        if (obj.value == 2) {
            $("#deductDiv").show();
        } else {
            $("#deductDiv").hide();
        }
    })

    // 省市联动
    form.on('select(provinceId)', function (obj) {
        triggerCityOptions(obj.value);
    })

    // 平台所属组织下1级部门联动
    form.on('select(plat)', function (obj) {
        // 如果所属平台为啄木鸟 ，默认勾选平台代收合同 如果所属平台非啄木鸟，默认勾选维修服务合同
        renderContractModel(obj.value);

        // 根据平台渲染子公司  如果是子公司合同则根据平台渲染子公司下拉框
        triggerSubCompanyOptions(obj.value);

        // 选择平台联动一级部门
        // triggerOneDeptOptions(obj.value);

        if (json.rank == 2) {
            // 选择平台联动一级渠道
            // _parent.reload();
        }
    })

    // 一级部门联动二级部门
    // form.on('select(oneDeptId)', function (obj) {
    //     triggerTwoDeptOptions(obj.value);
    // })

    form.on('radio(contractModel)', function (obj) {
        let currentSelectedPlat = $("#plat").find("option:selected").val();
        if (obj.value == 2 && (!zmnUtil.isEmptyNull(currentSelectedPlat)) && currentSelectedPlat == 10) {
            $("#subCompanyContractDiv").show();
        } else {
            $("#subCompanyContractDiv").hide();
        }
    })

    function triggerCityOptions(value) {
        let cityOptions = json.citys.filter(p => p.parentId == value).map(p => {
            return p.areaId == json.cityId ? '<option value="' + p.areaId + '" selected="selected">' + p.name + '</option>' : '<option value="' + p.areaId + '">' + p.name + '</option>';
        });
        cityOptions.unshift('<option value=""></option>');
        $('#cityId').html(cityOptions);
        form.render("select");
    }

    //点击取消

    function triggerSubCompanyOptions(value) {
        let oneDeptOptions = json.allSubCompanyList.filter(p => p.plat == value).map(p => {
            return p.companyId == json.obj.subCompanyId ? '<option value="' + p.companyId + '" selected="selected">' + p.fullName + '</option>' : '<option value="' + p.companyId + '">' + p.fullName + '</option>';
        });
        oneDeptOptions.unshift('<option value=""></option>');
        $('#subCompanyId').html(oneDeptOptions);
        form.render("select");
    }

    function refreshSelectOrganizeDeptTree() {

        zmnSelect.selectOrganizeDeptTree('deptId', {
            selectedValues: [json.obj.deptId == null ? '' : json.obj.deptId],//回显值，格式：数组[depId1,depId2]
            remote: { //远程获取下拉数据
                enable: true, //开关：true-开启；false-关闭
                url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
            },
            events: {
                /**
                 * 选择中事件
                 * @param values 已选中值，Array类型
                 */
                changing: function (values) {
                    selectedSalesmanDeptId = values[0];
                    // 调用 查询
                    let keyword = _salesman.staffName();
                    remoteCall("/channel/search/staff", toSplitStaffName(keyword), values[0], _salesman);
                }
            }
        });
        zmnSelect.selectOrganizeDeptTree('abutmentDeptId', {
            selectedValues: [json.obj.abutmentDeptId == null ? '' : json.obj.abutmentDeptId],//回显值，格式：数组[depId1,depId2]
            remote: { //远程获取下拉数据
                enable: true, //开关：true-开启；false-关闭
                url: json.SYS_MCC + '/common/dept/listDeptTree.action?orgId=' + 0, //服务url
            },
            events: {
                /**
                 * 选择中事件
                 * @param values 已选中值，Array类型
                 */
                changing: function (values) {
                    selectedAbutmentDeptId = values[0];
                    // 调用 查询
                    let keyword = _abutmenter.staffName();
                    remoteCall("/channel/search/staff", toSplitStaffName(keyword), values[0], _abutmenter);
                }
            }
        });

    }

    refreshSelectOrganizeDeptTree()

    /**
     * 渲染合同模式
     * @param plat
     */
    function renderContractModel(plat) {
        if (plat == 10) {
            $("input[name='contractModel'][value='1']").prop("checked", "checked");
            $("input[name='contractModel'][value='1']").attr("disabled", false);
        } else {
            $("input[name='contractModel'][value='2']").prop("checked", "checked");
            $("input[name='contractModel'][value='1']").attr("disabled", true);
        }

        $("#subCompanyContractDiv").hide();

        form.render(null);
    }

    if (json.obj.provinceId) {
        triggerCityOptions(json.obj.provinceId);
    }

    if (json.obj.plat) {
        // triggerOneDeptOptions(json.obj.plat);

        // 非啄木鸟平台只能维修服务合同模式
        if ((!zmnUtil.isEmptyNull(json.obj.plat)) && json.obj.plat != 10) {
            $("input[name='contractModel'][value='2']").prop("checked", "checked");
            $("input[name='contractModel'][value='1']").attr("disabled", true);
            form.render(null);
        }
    }
    // if (json.obj.oneDeptId) {
    //     triggerTwoDeptOptions(json.obj.oneDeptId);
    // }

    // 提交一级渠道
    form.on('submit(zmn-form-submit-one)', function (obj) {
        var t = zmnSelect.getXmSelect('deptId').getValue();
        var data = obj.field;

        let booleanFlag = judgeAndHandleData(data);
        if (!booleanFlag) {
            return false;
        }

        var url = "/channel/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (resp) {
                var message = resp.status == 200 ? "操作成功！" : resp.message;
                layer.msg(message);
                if (resp.status == 200) {
                    zmnPage.direct("/channel/detailOne.action?channelId=" + resp.data + "&addFlag=" + json.addFlag, 0);
                }
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });
        return false;
    });

    // 提交二级渠道
    form.on('submit(zmn-form-submit)', function (obj) {
        var data = obj.field;

        let booleanFlag = judgeAndHandleData(data);
        if (!booleanFlag) {
            return false;
        }

        var url = "/channel/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (resp) {
                var message = resp.status == 200 ? "操作成功！" : resp.message;
                layer.msg(message);
                if (resp.status == 200) {
                    if (data.promotionType != null && data.promotionType != undefined && data.promotionType == 3) {
                        getBaiduApiUrl(resp.data);
                    } else {
                        zmnPage.direct("/channel/detail.action?channelId=" + resp.data + "&addFlag=" + json.addFlag, 0);
                    }
                }
            },
            error: function (XMLHttpRequest, status, errorThrown) {
            }
        });
        return false;
    });

    function judgeAndHandleData(data) {
        data.companyName = _companyId.name();
        if (data.rank == 2) {
            data.parentName = _parent.name();
        }
        var selectDept = zmnSelect.getXmSelect('deptId').getValue();
        if (selectDept.length > 0) {
            data.deptName = selectDept[0].deptName;
        }

        var selectAbutmentDeptName = zmnSelect.getXmSelect('abutmentDeptId').getValue();
        if (selectAbutmentDeptName.length > 0) {
            data.abutmentDeptName = selectAbutmentDeptName[0].deptName;
        }

        data.salesmanName = _salesman.staffName();
        data.abutmenterName = _abutmenter.staffName();

        if (zmnUtil.isEmptyNull(data.abutmenter)) {
            layer.msg('运营责任人必填！', {icon: 2});
            return false;
        }

        if (zmnUtil.isEmptyNull(data.abutmentDeptId)) {
            layer.msg('运营部门必填！', {icon: 2});
            return false;
        }

        // 模式为平台代收合同时，子公司合同无意义
        if (data.contractModel == 1) {
            data.subCompanyId = null;
        }

        // 只有啄木鸟平台且选择维修服务合同时 子公司必填
        if (data.contractModel == 2 && data.plat == 10) {
            if (zmnUtil.isEmptyNull(data.subCompanyId)) {
                layer.msg('啄木鸟平台，合同模式为维修服务合同时，子公司合同必填！', {icon: 2});
                return false;
            }
        }

        if (data.rank == 2) {
            if (zmnUtil.isEmptyNull(data.parentId)) {
                layer.msg('二级渠道必须选择上级下单渠道!', {icon: 2});
                return false;
            }
        }

        if (data.rank == 2) {
            if (zmnUtil.isEmptyNull(data.parentSourceId)) {
                layer.msg('二级渠道必须选择上级来源渠道!', {icon: 2});
                return false;
            }
        }

        if (data.channelType != 7 && !data.companyId) {
            layer.msg('渠道公司必填!', {icon: 2});
            return false;
        }

        //获取checkbox[name='accessMode']的值
        if (data.rank == 2) {
            var accessIdentityArr = new Array();
            $("input:checkbox[name='accessIdentity']:checked").each(function (i) {
                accessIdentityArr[i] = $(this).val();
            });
            data.accessIdentity = accessIdentityArr.join(",");//将数组合并成字符串
            if (zmnUtil.isEmptyNull(data.accessIdentity)) {
                layer.msg('接入身份必填!', {icon: 2});
                return false;
            }
        }

        //获取checkbox[name='accessMode']的值
        var accessModeArr = new Array();
        $("input:checkbox[name='accessMode']:checked").each(function (i) {
            accessModeArr[i] = $(this).val();
        });
        data.accessMode = accessModeArr.join(",");//将数组合并成字符串
        if (zmnUtil.isEmptyNull(data.accessMode)) {
            layer.msg('接入方式必填!', {icon: 2});
            return false;
        }

        // 如果推广方式为无或者头条推广的话  清空百度API链接字段
        if (data.promotionType != null && data.promotionType != undefined) {
            if (data.promotionType == 1 || data.promotionType == 2) {
                data.orderLink = null;
            }
        }

        if (data.deptId == null || data.deptId == "") {
            layer.msg("商务部门不能为空", {"icon": 2});
            return false;
        }

        return true;
    }

    $('#baiduTips').click(function () {
        layer.open({
            title: '百度渠道注意事项',
            area: ['400px', '380px'],
            content: "1、百度落地页所需字段：报修项目（前台产品服务分类-前台一级产品-前台二级产品）、姓名、电话、城市（省-市-区）、详细地址、预约时间（颗粒度：日）\n" +
                "\n" +
                "<br//>2、线索推送给呼叫中心的情况\n" +
                "\n" +
                "<br//>（1）百度所需字段缺失\n" +
                "\n" +
                "<br//>（2）产品信息错误\n" +
                "\n" +
                "<br//>（3）地址解析失败（根据百度地图未解析成功）\n" +
                "\n" +
                "<br//>3、业务测试工单未生成工单自查步骤\n" +
                "\n" +
                "<br//>（1）落地页填写信息是否标准，是否有遗漏\n" +
                "\n" +
                "<br//>（2）对应百度账号内是否有线索\n" +
                "\n" +
                "<br//>（3）百度对应API接口是否准确（路径：基木鱼后台-账户设置-线索接收-推送接口配置）",
            btn: null
        });
    });

    //对外暴露的接口
    exports('channel_detail', {});
});

function getBaiduApiUrl(channelId) {
    // 查询微信永久二维码URL, 如存在直接返回, 不存在生成新的
    let url = json.ZMN_URL_ENV + 'gateway-api.xiujiadian.com/oms/api/capi/baidu/v1/getChannelAPIUrl';
    // let url = 'http://test2-gateway-api.xiujiadian.com/oms/api/capi/baidu/v1/getChannelAPIUrl';
    let param = {
        "body": {
            "channelId": channelId
        }
    }

    $.ajax({
        // async: false,
        contentType: "application/json;charset=UTF-8",
        type: "POST",
        url: url,
        dataType: "JSON",
        data: JSON.stringify(param),
        xhrFields: {withCredentials: true}, //设置请求可以携带cookie
        crossDomain: true, success: function (resp) {
            if (resp.status == 200) {
                let url = resp.data;
                if (!zmnUtil.isEmptyNull(url)) {
                    modifyBaiduApiUrl(channelId, url);
                }
            } else {
                layer.msg(resp.message);
            }
        },
        error: function (XMLHttpRequest, status, errorThrown) {
        }
    });
}

function modifyBaiduApiUrl(channelId, orderLink) {
    let url = "/channel/updateOrderLink.action";
    var $ = layui.$;
    $.ajax({
        type: "POST", url: url,
        dataType: "json", data: {channelId: channelId, orderLink: orderLink},
        success: function (result) {
            zmnPage.direct("/channel/detail.action?channelId=" + channelId + "&addFlag=" + json.addFlag, 0);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}